package com.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
public class ShiroController {

    @RequestMapping({"/","/index"})
    public String test1(Model model){

        model.addAttribute("msg","Hello,Shiro");
        return "index";

    }

    @RequestMapping("/user/add")
    public String addUser(){
        return "user/add";
    }

    @RequestMapping("/user/del")
    public String delUser(){
        return "user/del";
    }

    @RequestMapping("/user/select")
    public String selectUser(){
        return "user/select";
    }

    @RequestMapping("/doLogin")
    public String doLogin(){

        return "login";
    }

    @GetMapping("/login")
    public String login(String username,String password,Model model){
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        try {
            subject.login(token);

            return "index";
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            model.addAttribute("message","用户名错误！");
            return "login";
        }catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            model.addAttribute("message","密码错误！");
            return "login";
        }
    }

    @RequestMapping("/unauth")
    @ResponseBody
    public String unauth(){
        return "未经授权，暂无法访问！";
    }

}
